package com.demo.cms.action.demo;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.codehaus.jackson.JsonProcessingException;

import com.demo.common.ImageUtils;
import com.demo.webapp.kcfinder.KCFinderStatics;
import com.demo.webapp.kcfinder.action.ActionSupport;
import com.demo.webapp.kcfinder.action.DownloadFileInfoAware;
import com.demo.webapp.kcfinder.action.UploadFileItemAware;
import com.demo.webapp.kcfinder.context.ActionContext;
import com.demo.webapp.kcfinder.model.DownloadInfo;
import com.demo.webapp.kcfinder.model.Folder;
import com.demo.webapp.kcfinder.utils.DelegateFileFilter;
import com.demo.webapp.kcfinder.utils.FileCustomNameFilter;
import com.demo.webapp.kcfinder.utils.FileExtensionsFilter;
import com.demo.webapp.kcfinder.utils.FileTypeFilder;

/**
 * KCFiinder的浏览Action
 * 该Action提供KCFinder的所有功能
 * <table>
 * 	<tr><td>1.show</td><td>页面展示</td></tr>
 *  <tr><td>2.init</td><td>页面数据初始化</td></tr>
 *  <tr><td>3.chDir</td><td>查询指定文件夹内所有文件</td></tr>
 * </table>
 * 
 * @author ryuu.kk
 *
 */
public class BrowseAction extends ActionSupport implements DownloadFileInfoAware, UploadFileItemAware {
	
	/**
	 * 文件信息
	 */
	private DownloadInfo downloadInfo;
	
	/**
	 * 上传文件信息
	 */
	private List<FileItem> fileItems;
	
	/**
	 * 文件保存地址
	 */
	private String filePath;
	
	/**
	 * 目标地址
	 */
	private String target;
	
	/**
	 * 缩略图大小 
	 * height : 100
	 * width  : 100
	 */
	private int thumbSize[] = {100, 100};
	
	/**
	 * 中图大小
	 * height : 250
	 * width  : 150
	 */
	private int mediumSize[] = {250, 150};
	
	public static Map<String, List<String>> fileTypeMap;
	
	static {
		fileTypeMap = new HashMap<String, List<String>>(){
			/**
			 * 序列化ID
			 */
			private static final long serialVersionUID = 9032961969343641257L;
		{
			List<String> images = new ArrayList<String>(){
				private static final long serialVersionUID = 1L;
			{
				add("png");
				add("jpg");
				add("jpeg");
				add("bmp");
				add("jpe");
			}};
			
			List<String> files = new ArrayList<String>(){
				private static final long serialVersionUID = 1L;
			{
				add("*");
			}};
			
			put("images", images);
			put("files", files);
			
		}};
	}
	
	/**
	 * KCFinder页面展示
	 * @return SUCCESS
	 */
	public String show() {
		ActionContext context = ActionContext.getContext();
		HttpServletResponse response = context.getResponse();
		ServletContext servletContext = context.getServletContext();
		Locale locale = context.getLocale();
		//取得文件类型
		String type = context.getValue("type", "images");
		//取得初始文件夹
		String dir = context.getValue("dir", "");
		// 访问路径传递,页面将得到dir路径,并且有init方法初始化数据
		context.getRequest().setAttribute("dir", dir);
		
		Cookie[] cookies = context.getCookies();
		String keyOrder = "KCFINDER_order";
		String keyView = "KCFINDER_view";
		//默认Order by的name被选中
		Cookie cookie_order = new Cookie(keyOrder, "name");
		Cookie cookie_view = new Cookie(keyView, "thumbs");
		if (cookies!= null && cookies.length > 0) {
			for (Cookie c : cookies) {
				if (keyOrder.equals(c.getName())) {
					cookie_order = c;
				}
				if (keyView.equals(c.getName())) {
					cookie_view = c;
				}
			}
		}
		response.addCookie(cookie_order);
		response.addCookie(cookie_view);

		return SUCCESS;
	}
	
	private static void add(String string) {
		// TODO Auto-generated method stub
		
	}

	/**
	 * 文档初始化
	 * KCFinder的初始化数据
	 * 其中包含文档和文件的数据
	 * @return json结果
	 * @throws IOException IO异常
	 * @throws JsonProcessingException Json处理异常
	 */
	public String init() throws JsonProcessingException, IOException {
		
		ActionContext context = ActionContext.getContext();
		
		HttpServletResponse response = context.getResponse();
		ServletContext servletContext = context.getServletContext();
		Locale locale = context.getLocale();
		//取得文件类型
		String type = context.getValue("type", "images");
		//取得初始文件夹
		String dir = context.getValue("dir", "");
		// 公共基础地址
		dir = getAbstractPath(dir);
		
		if (!context.isAllowPath(dir)) {
			this.push("tree", new Folder());
			this.push("files", new ArrayList<com.demo.webapp.kcfinder.model.File>());
			this.push("dirWritable", true);
			this.push("error", "不允许访问<<"+ dir + ">>. 如需访问,请设置配置文件的项'kcfinder.allow.path'.");
			return "error";
		}
		//String dir = context.getPublicPath();
		
		String realPath = servletContext.getRealPath(dir);

		File publicFolder = new File(realPath);
		if (!publicFolder.exists()) {
			publicFolder.mkdirs();
		}
		Folder folder = new Folder();
		
		getFolder(folder, publicFolder, new FileTypeFilder(FileTypeFilder.TYPE.FOLDER));
		//递归文件夹
		
		List<com.demo.webapp.kcfinder.model.File> files = null;
		
		List<String> fileType = fileTypeMap.get(type);
		FilenameFilter filter = null;
		//根据类型查找并过滤文件
		if ("images".equals(type)) {
			//过滤缩略图:不以前缀开头,并且是文件的
			filter = new DelegateFileFilter(DelegateFileFilter.FILTER_RULE_STRICT, new FileCustomNameFilter(true, "(?:(?!^" + KCFinderStatics.THUMB_PREFIX + ").)*"), new FileCustomNameFilter(true, "(?:(?!^" + KCFinderStatics.MEDIUM_PREFIX + ").)*"), new FileTypeFilder(FileTypeFilder.TYPE.FILE));
		} else if ("files".equals(type)) {
			filter = new DelegateFileFilter(new FileExtensionsFilter("**"));
		}
		List<com.demo.webapp.kcfinder.model.File> fileList = getFiles(publicFolder, filter);
		
		//folder.setFiles(fileList);
		//String result = "{\"tree\":{\"name\":\"images\",\"readable\":true,\"writable\":false,\"removable\":false,\"hasDirs\":true,\"dirs\":[{\"name\":\"Photos from Bulgaria\",\"readable\":true,\"writable\":false,\"removable\":false,\"hasDirs\":false},{\"name\":\"public\",\"readable\":true,\"writable\":true,\"removable\":false,\"hasDirs\":false,\"current\":true, \"dirs\":[{\"name\":\"123\",\"readable\":true,\"writable\":true,\"removable\":true,\"hasDirs\":false}]},{\"name\":\"Sonisphere - Sofia 2010\",\"readable\":true,\"writable\":false,\"removable\":false,\"hasDirs\":false}]},\"files\":[{\"name\":\"Blue hills(1).jpg\",\"size\":28521,\"mtime\":1333089452,\"date\":\"03/30/2012 06:37 AM\",\"readable\":true,\"writable\":true,\"bigIcon\":true,\"smallIcon\":true,\"thumb\":true,\"smallThumb\":false},{\"name\":\"Blue hills.jpg\",\"size\":28521,\"mtime\":1333089423,\"date\":\"03/30/2012 06:37 AM\",\"readable\":true,\"writable\":true,\"bigIcon\":true,\"smallIcon\":true,\"thumb\":true,\"smallThumb\":false},{\"name\":\"close_button.png\",\"size\":858,\"mtime\":1333086221,\"date\":\"03/30/2012 05:43 AM\",\"readable\":true,\"writable\":true,\"bigIcon\":true,\"smallIcon\":true,\"thumb\":false,\"smallThumb\":true}],\"dirWritable\":true}";
		//JsonNode node = mapper.readTree(result);
		//String tree = result;
		this.push("tree", folder);
		this.push("files", fileList);
		this.push("dirWritable", true);
		return SUCCESS;
	}
	
	/**
	 * 查看文件夹下所有文件
	 * @return SUCCESS
	 */
	public String chDir() {
		
		ActionContext context = ActionContext.getContext();
		
		HttpServletResponse response = context.getResponse();
		ServletContext servletContext = context.getServletContext();
		Locale locale = context.getLocale();
		//取得文件类型
		String type = context.getValue("type", "images");
		//取得初始文件夹
		String dir = context.getValue("dir", context.getPublicPath());
		// 公共基础地址
		dir = getAbstractPath(dir);
		
		String realPath = servletContext.getRealPath(dir);
		
		File publicFolder = new File(realPath);
		
		List<com.demo.webapp.kcfinder.model.File> files = null;
		
		List<String> fileType = fileTypeMap.get(type);
		FilenameFilter filter = null;
		
		//根据类型查找并过滤文件
		if ("images".equals(type)) {
			//过滤缩略图
			filter = new DelegateFileFilter(
					DelegateFileFilter.FILTER_RULE_STRICT,
					new FileCustomNameFilter(true, "(?:(?!^" + KCFinderStatics.THUMB_PREFIX + ").)*"),
					new FileCustomNameFilter(true, "(?:(?!^" + KCFinderStatics.MEDIUM_PREFIX + ").)*"),
					new FileTypeFilder(FileTypeFilder.TYPE.FILE));
		} else if ("files".equals(type)) {
			filter = new DelegateFileFilter(new FileExtensionsFilter("**"));
		}
		
		files = getFiles(publicFolder, filter);
		this.push("files", files);
		this.push("dirWritable", true);
		return SUCCESS;
	}
	
	/**
	 * 查看文件缩略图
	 * @return SUCCESS
	 * @throws IOException 
	 */
	public String thumb() throws IOException {
		
		ActionContext context = ActionContext.getContext();
		//http://localhost/cms/kcfinder/browse.kc?type=images&lng=en&act=thumb&file=demo.jsp&dir=LEVEL%2FLEVEL1&stamp=177c62cf6053ad39b113017dda90518d
		ServletContext servletContext = context.getServletContext();
		
		Locale locale = context.getLocale();
		String type = downloadInfo.getType();
		String fileName = downloadInfo.getFileName();
		String dir = downloadInfo.getDir();
		String stamp = downloadInfo.getStamp();
		//downloadInfo.setContentType("");
		String realPath = servletContext.getRealPath(getAbstractPath(KCFinderStatics.THUMB_PATH + "/" + dir));
		
		if (realPath.charAt(realPath.length() - 1) != '/') {
			realPath += "/";
		}
		// 读取缩略图
		File file = new File(realPath + fileName);
		
		//文件不存在,并且文件不以缩略图前缀出现
		if (!file.exists()) {
			// 不存在时先创建缩略图
			File oriFile = new File(servletContext.getRealPath(getAbstractPath(dir + "/" + fileName)));
			if (!oriFile.exists()) {
				// 原始文件不存在,直接退出
				return "none";
			}
			//写入缩略图
			thumbWriter(oriFile, dir, thumbSize[0], thumbSize[1]);
		}
			
		
		//取得图片流
		//java.io.InputStream inputStream = new java.io.FileInputStream(file);
		
		//byte[] thumBits = ImageUtils.toThumbnail(file, thumbSize[0], thumbSize[1]);
		FileInputStream is = new FileInputStream(file);  
		//RandomAccessFile file = new RandomAccessFile();
		this.push(is);
		return SUCCESS;
	}
	
	/**
	 * 创建新文件夹
	 * 返回空JSON数据
	 * "{}"
	 * @return SUCCESS
	 * @throws IOException 
	 */
	public String newDir() throws IOException {
		
		ActionContext context = ActionContext.getContext();
		ServletContext servletContext = context.getServletContext();
		
		String type = context.getValue("type", "images");
		String dir = context.getValue("dir", "");
		String newDir = context.getValue("newDir", "");
		// 公共基础地址
		dir = getAbstractPath(dir);
		//newDir = getAbstractPath(newDir);
		String path = servletContext.getRealPath(dir);
		
		File file = new File(path);
		File newFile = null;
		if (file.exists() && file.isDirectory()) {
			newFile = new File(file.getPath() + "/" + newDir);
			if (!newFile.exists()) {
				newFile.mkdir();
			}
		}
		push("", "");
		this.push("dirWritable", true);
		return SUCCESS;
	}
	
	/**
	 * 展示指定文件夹下所有文件夹
	 * 返回JSON类型
	 * 例如：
	 * {"dirs":[{"name":"aaa","readable":true,"writable":true,"removable":true,"hasDirs":false}]}
	 * @return SUCCESS
	 */
	public String expand() {
		
		ActionContext context = ActionContext.getContext();
		ServletContext servletContext = context.getServletContext();
		
		String type = context.getValue("type", "images");
		String dir = context.getValue("dir", "");
		// 公共基础地址
		dir = getAbstractPath(dir);
		//展开dir下所有文件夹
		String path = servletContext.getRealPath(dir);
		File file = new File(path);
		Folder folder = new Folder();
		getFolder(folder, file, new FileTypeFilder(FileTypeFilder.TYPE.FOLDER));
		
		this.push("dirs", folder.getDirs());
		//是否可写入
		this.push("dirWritable", true);
		return SUCCESS;
	}
	
	/**
	 * 删除指定文件
	 * @return SUCCESS
	 */
	public String delete() {
		ActionContext context = ActionContext.getContext();
		ServletContext servletContext = context.getServletContext();
		
		String type = context.getValue("type", "images");
		String dir = context.getValue("dir", context.getPublicPath());
		String file = context.getValue("file", "");
		if (dir.charAt(dir.length() - 1) != '/') {
			dir += "/";
		}
		filePath = servletContext.getRealPath(getAbstractPath(dir));
		
		File delFile = new File(filePath + "/" + file);
		
		if (delFile.exists()) {
			delFile.delete();
		}
		// 同时删除缩略图(如果存在)
		String path1 = servletContext.getRealPath(getAbstractPath(KCFinderStatics.THUMB_PATH + "/" + dir));
		File dFile1 = new File(path1 + "/" + file);
		if (dFile1.exists()) {
			dFile1.delete();
		}
		// 同时删除中图(如果存在)
		String path2 = servletContext.getRealPath(getAbstractPath(KCFinderStatics.MEDIUM_PATH + "/" + dir));
		File dFile2 = new File(path2 + "/" + file);
		if (dFile2.exists()) {
			dFile2.delete();
		}
		this.push("", "");
		return SUCCESS;
	}
	

	/**
	 * 批量删除文件
	 * @return
	 */
	public String rm() {
		
		ActionContext context = ActionContext.getContext();
		ServletContext servletContext = context.getServletContext();
		HttpServletRequest request = context.getRequest();
		HttpServletResponse response = context.getResponse();
		
		String type = context.getValue("type", "images");
		String dir = context.getValue("dir", context.getPublicPath());
		String[] files = context.getValues("files[]");
		// 公共基础地址
		//dir = getAbstractPath(dir);
		if (files != null) {
			for (String f : files) {
				String file = servletContext.getRealPath(getAbstractPath(f));
				File delFile = new File(file);
				
				if (delFile.exists()) {
					delFile.delete();
				}
				
				// 同时删除缩略图(如果存在)
				String path1 = servletContext.getRealPath(getAbstractPath(KCFinderStatics.THUMB_PATH + "/" + f));
				File dFile1 = new File(path1);
				if (dFile1.exists()) {
					dFile1.delete();
				}
				// 同时删除中图(如果存在)
				String path2 = servletContext.getRealPath(getAbstractPath(KCFinderStatics.MEDIUM_PATH + "/" + f));
				File dFile2 = new File(path2);
				if (dFile2.exists()) {
					dFile2.delete();
				}
			}
		}
		
		this.push("", "");
		return SUCCESS;
	}
	
	/**
	 * 删除文件夹
	 * @return
	 */
	public String deleteDir() {
		ActionContext context = ActionContext.getContext();
		ServletContext servletContext = context.getServletContext();
		
		String type = context.getValue("type", "images");
		String dir = context.getValue("dir", "");
		
		filePath = servletContext.getRealPath(getAbstractPath(dir));
		// 原始文件删除
		delete(new File(filePath));
		// 缩略图删除(如果存在)
		delete(new File(servletContext.getRealPath(getAbstractPath(KCFinderStatics.THUMB_PATH + "/" + dir))));
		// 中图删除(如果存在)
		delete(new File(servletContext.getRealPath(getAbstractPath(KCFinderStatics.MEDIUM_PATH + "/" + dir))));
		
		this.push("", "");
		return SUCCESS;
	}
	
	/**
	 * 重命名文件夹
	 * @return
	 */
	public String renameDir() {
		ActionContext context = ActionContext.getContext();
		ServletContext servletContext = context.getServletContext();
		
		String type = context.getValue("type", "images");
		String dir = context.getValue("dir", "");
		String newName = context.getValue("newName", "");
		String realDir = servletContext.getRealPath(getAbstractPath(dir));
		
		File oldDir = new File(realDir);
		File newDir = new File(oldDir.getParentFile().getPath() + "/" + newName);
		if (oldDir.exists() && oldDir.isDirectory()) {
			oldDir.renameTo(newDir);
		}
		if (type.equals("images")) {
			// 重命名缩略图和中图
			String rDir = servletContext.getRealPath(getAbstractPath(KCFinderStatics.THUMB_PATH + dir));
			File oldThumbDir = new File(rDir);
			File newThumbDir = new File(oldThumbDir.getParentFile().getPath() + "/" + newName);
			if (oldThumbDir.exists() && oldThumbDir.isDirectory()) {
				oldThumbDir.renameTo(newThumbDir);
			}
			String mDir = servletContext.getRealPath(getAbstractPath(KCFinderStatics.MEDIUM_PATH + dir));
			File oldMediumDir = new File(mDir);
			File newMediumDir = new File(oldMediumDir.getParentFile().getPath() + "/" + newName);
			if (oldMediumDir.exists() && oldMediumDir.isDirectory()) {
				oldMediumDir.renameTo(newMediumDir);
			}
		}
		this.push("", "");
		return SUCCESS;
	}
	
	/**
	 * 选择的文件下载
	 * 如果所选单文件,直接下载
	 * 如果多选文件,则压缩后下载
	 * @return
	 * @throws FileNotFoundException 
	 */
	public String downloadSelected() throws FileNotFoundException {
		ActionContext context = ActionContext.getContext();
		ServletContext servletContext = context.getServletContext();
		String type = context.getValue("type", "images");
		String dir = context.getValue("dir", "");
		String realDir = servletContext.getRealPath(getAbstractPath(dir));
		String[] files = context.getValues("files");
		if (files != null && files.length == 1) {
			//单一文件下载
			File file = new File(realDir + "/" + files[0]);
			if (file.exists() && file.isFile()) {
				FileInputStream inputStream = new FileInputStream(file);
				//ByteArrayInputStream is = new ByteArrayInputStream(thumBits);
				this.push(downloadInfo);
				this.push(inputStream);
			}
		}
		
		return SUCCESS;
	}
	
	/**
	 * 单文件下载
	 * @return
	 * @throws FileNotFoundException
	 */
	public String download() throws FileNotFoundException {
		ActionContext context = ActionContext.getContext();
		ServletContext servletContext = context.getServletContext();
		String type = context.getValue("type", "images");
		String dir = context.getValue("dir", "");
		String realDir = servletContext.getRealPath(getAbstractPath(dir));
		String file = context.getValue("file", "");
		if (StringUtils.isNotEmpty(file)) {
			File downloadFile = new File(realDir + "/" + file);
			FileInputStream inputStream = new FileInputStream(downloadFile);
			//ByteArrayInputStream is = new ByteArrayInputStream(thumBits);
			this.push(downloadInfo);
			this.push(inputStream);
			return SUCCESS;
		}
		return "none";
	}
	
	/**
	 * 上传文件
	 * @return
	 * @throws Exception 
	 */
	public String upload() throws Exception {
		
		ActionContext context = ActionContext.getContext();
		ServletContext servletContext = context.getServletContext();
		HttpServletRequest request = context.getRequest();
		HttpServletResponse response = context.getResponse();
		
		String type = context.getValue("type", "");
		String dir = context.getValue("dir", "");
		// 公共基础地址
		//dir = getAbstractPath(dir);
		// 生成缩略图,默认images类型都要生成缩略图
		boolean thumb = context.getValue("thumb", type.equals("images"));
		boolean medium = context.getValue("medium", type.equals("images"));
		this.filePath = servletContext.getRealPath(getAbstractPath(dir));
		if (this.fileItems != null && type.equals("images")) {
			for (FileItem item : fileItems) {
				//如果是图片,则生成缩略图和中图
				String fileName = writer(item, dir, thumb, medium);
				this.push("fileName", fileName);
			}
		}
		
		return SUCCESS;
	}
	
	
	/**
	 * 删除文件夹下所有文件及子文件夹
	 * @param file java.io.File
	 */
	private void delete(File file) {
		if (file != null && file.exists()) {
			if (file.isDirectory()) {
				File[] files = file.listFiles();
				if (files != null && files.length > 0) {
					for (File f : files) {
						delete(f);
					}
				}
			} 
			file.delete();
		}
	}
	
	public String writer(FileItem item, String dir, boolean thumbable, boolean mediumable) throws Exception {
		
		//~~ 取得上传文件参数 =====================================================================
        String fileName = item.getName();
        
        //String fieldName = item.getFieldName();
        //String contentType = item.getContentType();
       // boolean isInMemory = item.isInMemory();
        
        File file = null;
        //写文件
        dir = dir.replace("\\", "/");
        
        // 获得绝对路径
        String filePath = ActionContext.getContext().getServletContext().getRealPath(getAbstractPath(dir));
        if (filePath.charAt(filePath.length() - 1) != '/') {
        	filePath += "/";
        }
        if( fileName.lastIndexOf("/") >= 0 ){
        	file = new File( filePath + fileName.substring( fileName.lastIndexOf("/"))) ;
        } else {
        	file = new File( filePath + fileName.substring(fileName.lastIndexOf("/") + 1)) ;
        }
        //写入文件
        item.write(file);
        
		if (thumbable) {
			// 生成缩略图
			thumbWriter(file, dir, thumbSize[0], thumbSize[1]);
		}
		
		if (mediumable) {
			// 生成中图
			mediumWriter(file, dir, mediumSize[0], mediumSize[1]);
		}
        return fileName;
	}
	
	/**
	 * 缩略图写入方法
	 * @param originalFile 原图文件
	 * @param width 缩略图宽度
	 * @param height 缩略图高度
	 * @throws IOException IO异常
	 */
	public void thumbWriter(File originalFile, String dir, int width, int height) throws IOException {
		String thumbName = originalFile.getName();
		dir = dir.replace("\\", "/");
		
		// 获得绝对路径
        if (dir.charAt(dir.length() -1) != '/') {
        	dir += "/";
        }
        String filePath = ActionContext.getContext().getServletContext().getRealPath(getAbstractPath(KCFinderStatics.THUMB_PATH + "/" + dir));
        File thumDir = new File(filePath);
		if (!thumDir.exists()) {
			thumDir.mkdirs();
		}
		// 生成缩略图
		File thumFile = new File(filePath + "/" + thumbName);
		if (thumFile.exists()) {
			thumFile.delete();
		}
		thumFile.createNewFile();
		byte[] thumBits = ImageUtils.toThumbnail(originalFile, width, height, true);
		ByteArrayInputStream is = new ByteArrayInputStream(thumBits);
		BufferedInputStream in = null;
		BufferedOutputStream out = null;
		try {
			in = new BufferedInputStream(is);
			out = new BufferedOutputStream(new FileOutputStream(thumFile));
			IOUtils.copy(in, out);
		} finally {
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
					// ignore
				}
			}
			if (out != null) {
				try {
					out.close();
				} catch (IOException e) {
					// ignore
				}
			}
		}
	}
	
	/**
	 * 中图写入方法
	 * @param originalFile 原图文件
	 * @param width 缩略图宽度
	 * @param height 缩略图高度
	 * @throws IOException IO异常
	 */
	public void mediumWriter(File originalFile, String dir, int width, int height) throws IOException {
		
		String mediumName = originalFile.getName();
		dir = dir.replace("\\", "/");
		
		// 获得绝对路径
		if (dir.charAt(dir.length() -1) != '/') {
			dir += "/";
        }
		// 获得绝对路径
        String filePath = ActionContext.getContext().getServletContext().getRealPath(getAbstractPath(KCFinderStatics.MEDIUM_PATH + "/" + dir));
        File mediumDir = new File(filePath);
		if (!mediumDir.exists()) {
			mediumDir.mkdirs();
		}
		// 生成缩略图
		File mediumFile = new File(filePath + "/" + mediumName);
		
		if (!mediumFile.exists()) {
			mediumFile.delete();
		}
		mediumFile.createNewFile();
		byte[] mediumBits = ImageUtils.toThumbnail(originalFile, width, height, true);
		ByteArrayInputStream is = new ByteArrayInputStream(mediumBits);
		BufferedInputStream in = null;
		BufferedOutputStream out = null;
		try {
			in = new BufferedInputStream(is);
			out = new BufferedOutputStream(new FileOutputStream(mediumFile));
			IOUtils.copy(in, out);
		} finally {
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
					// ignore
				}
			}
			if (out != null) {
				try {
					out.close();
				} catch (IOException e) {
					// ignore
				}
			}
		}
	}
	
	public void getFolder(Folder folder, File file, FileFilter filter) {
		
		folder.setHasDirs(false);
		folder.setName(file.getName());
		folder.setReadable(true);
		folder.setWritable(true);
		folder.setRemovable(true);
		File[] files = null;
		if (file != null) {
			files = file.listFiles(filter);
		}
		if (files != null && files.length > 0) {
			folder.setHasDirs(true);
            for (File f : files) {
            	Folder childfolder = new Folder();
            	folder.addFolder(childfolder);
            	getFolder(childfolder, f, filter);
            }
		}
	}

	public List<com.demo.webapp.kcfinder.model.File> getFiles(File file, FilenameFilter filter) {
		
		List<com.demo.webapp.kcfinder.model.File> fileList = new ArrayList<com.demo.webapp.kcfinder.model.File>();
		
		File[] files = null;
		if (file != null) {
			files = file.listFiles(filter);
		}
		if (files != null && files.length > 0) {
			for (File f : files) {
				com.demo.webapp.kcfinder.model.File kcFile = new com.demo.webapp.kcfinder.model.File();
				String name = f.getName();
				int size = (int) f.getTotalSpace();
				Date date = new Date(f.lastModified());
				long mtime = f.lastModified();
				kcFile.setBigIcon(false);
				kcFile.setDate(date);
				kcFile.setMtime(mtime);
				kcFile.setReadable(true);
				kcFile.setSize(size);
				kcFile.setSmallThumb(true);
				kcFile.setThumb(true);
				kcFile.setWritable(true);
				kcFile.setName(name);
				fileList.add(kcFile);
			}
		}
		
		return fileList;
	}
	@Override
	public void setDwonloadInfo(DownloadInfo info) {
		push(info);
		this.downloadInfo = info;
	}
	
	@Override
	public void setFileItems(List<FileItem> items) {
		this.fileItems = items;
	}
	
	public String getAbstractPath(String dir) {
		ActionContext context = ActionContext.getContext();
		// 公共基础地址
		//dir = context.getServletContext().getRealPath(context.getPublicPath() + "/" + dir);
		dir = context.getPublicPath() + "/" + dir;
		return dir;
	}
	
	public static void main(String[] args) {  
        String[] strs = {  
                "abc1232",  "wwwadsf",  
                "awwwfas",  "wwadfsf",  
                "", "ww", " ", "www"  
            };  
        String regex = "(?:(?!^www).)*";  
        for(String str : strs) {  
            System.out.printf("%-7s %s%n", str, str.matches(regex));  
        }  
    }  
	
	
	
	
	
	
	
}
